﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace frag_boardgame
{
    /// <summary>
    /// This class is handaling the Board unit
    /// </summary>
    [DataContract]
    public class Board
    {

        [DataMember]
        private Square[][] board;  //the multidimenstional array that representing the board

        [DataMember]
        private int _height;

        [DataMember]
        private int _width;

        /// <summary>
        /// Constructor: Create a new board 
        /// </summary>
 
        public Board(int row,int col)
        {
            board = new Square[row][];
            for (int i = 0; i < row; i++)
            {
                board[i] = new Square[col];
                for (int j = 0; j < col; j++)
                {
                    Square square = new Square(i, j);
                    board[i][j] = square;
                }
            }
            _height= row;
            _width= col;

        }

        public Board() : this(16,25)
        {
          
        }



        /// <summary>
        ///  Get a square from a given pos
        /// </summary>
        /// <param name="i">Row</param>
        /// <param name="j">Column</param>
        /// <returns></returns>
        public Square GetSquare(int i, int j)
        {
            return board[i][j];
        }



        public int Width
        {
            get
            {
                return _width;
            }
        }

        public int Height
        {
            get
            {
                return _height;
            }
        }


        public int GetDistance(Player player1, Player player2)
        {
            return Math.Abs(player1.Row - player2.Row) +
                Math.Abs(player1.Column - player2.Column);
        }


        // override object.Equals
        public override bool Equals(object obj)
        {
            Board b = obj as Board;
            if (b == null) return false;

            if (b.Height != Height || b.Width != b.Width)
                return false;

            for (int i = 0; i < Height; i++)
            {
                for (int j = 0; j < Width; j++)
                {
                    if (!Equals(b.board[i][j], board[i][j]))
                        return false;
                }
            }

            return true;
        }

        // override object.GetHashCode
        public override int GetHashCode()
        {
            int res = 0;
            for (int i = 0; i < Height; i++)
            {
                for (int j = 0; j < Width; j++)
                {
                    res ^= i;
                    res ^= j;
                    res ^= (board[i][j] == null) ? 0 : board[i][j].GetHashCode();
                }
            }
            return res;
        }


    }
}
